package thrift

import (
	"fmt"
	"gitee.com/tietang/terrace-go/v2/example/apis/thrift/gen/handlers"
	"github.com/apache/thrift/lib/go/thrift"
	"os"
)

func NewClient(serviceName, addr string) (client *thrift.TStandardClient) {
	protocolFactory := thrift.NewTBinaryProtocolFactoryDefault()
	//transportFactory := thrift.NewTBufferedTransportFactory(8192)
	transportFactory := thrift.NewTFramedTransportFactory(thrift.NewTTransportFactory())

	socketTrans, err := thrift.NewTSocket(addr)
	if err != nil {
		fmt.Fprintln(os.Stderr, "error resolving address:", err)
		os.Exit(1)
	}
	trans, err := transportFactory.GetTransport(socketTrans)
	if err != nil {
		fmt.Fprintln(os.Stderr, "error resolving address:", err)
		os.Exit(1)
	}
	//trans := socketTrans

	//inProtocol := protocolFactory.GetProtocol(trans)
	//oprot := protocolFactory.GetProtocol(trans)
	var inputProtocol, outputProtocol thrift.TProtocol
	inputProtocol = protocolFactory.GetProtocol(trans)
	inputProtocol = thrift.NewTMultiplexedProtocol(inputProtocol, serviceName)
	outputProtocol = protocolFactory.GetProtocol(trans)
	outputProtocol = thrift.NewTMultiplexedProtocol(outputProtocol, serviceName)

	if err := trans.Open(); err != nil {
		fmt.Fprintln(os.Stderr, "Error opening socket to ", addr, " ", err)
		os.Exit(1)
	}
	//defer trans.Close()
	client = thrift.NewTStandardClient(inputProtocol, outputProtocol)
	return client

}

func NewAccountClinet(addr string) *handlers.AccountHandlerClient {
	client := handlers.NewAccountHandlerClient(NewClient("account", addr))
	return client
}
